<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElDialog,
  ElProgress,
  ElDescriptions,
  ElDescriptionsItem,
  ElSelect,
  ElOption,
  ElCard,
  ElCollapse,
  ElCollapseItem,
  ElInput,
  ElIcon,
} from "element-plus";
import { Loading } from "@element-plus/icons-vue";
import { Refresh, Plus, View } from "@element-plus/icons-vue";
import {
  getTaskList,
  getTaskDetail,
  createTask,
  pauseTask,
  resumeTask,
  cancelTask,
  getScenarioList,
  getTaskLogs,
  getReportData,
  generateReport,
  buildReportDownloadUrl,
} from "../servers";
import TaskResult from "./TaskResult.vue";
import ProgressBar from "@/components/ProgressBar/index.vue";

const props = defineProps<{
  task: string;
}>();

const loading = ref(false);
const taskList = ref<any[]>([]);
const searchFormRef = ref<DynamicFormInstance>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const searchForm = reactive({
  status: "",
  start_date: "",
  end_date: "",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "status",
    name: "状态",
    type: "select",
    labelWidth: "60px",
    placeholder: "选择状态",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "待执行", value: "pending" },
        { label: "运行中", value: "running" },
        { label: "已暂停", value: "paused" },
        { label: "已完成", value: "completed" },
        { label: "已失败", value: "failed" },
      ],
    },
  },
  {
    key: "start_date",
    name: "开始日期",
    type: "date",
    labelWidth: "80px",
    params: { clearable: true },
  },
  {
    key: "end_date",
    name: "结束日期",
    type: "date",
    labelWidth: "80px",
    params: { clearable: true },
  },
];

const getStatusTag = (status: string) => {
  const statusMap: Record<string, any> = {
    pending: { text: "待执行", type: "info" },
    running: { text: "运行中", type: "warning" },
    paused: { text: "已暂停", type: "warning" },
    completed: { text: "已完成", type: "success" },
    failed: { text: "已失败", type: "danger" },
  };
  return statusMap[status] || { text: status, type: "info" };
};

const columns = ref<TableColumn[]>([
  { label: "任务ID", prop: "task_id", width: 280, show: true },
  { label: "任务名称", prop: "task_name", minWidth: 200, show: true },
  { label: "目标URL", prop: "target_url", minWidth: 250, show: true },
  {
    label: "状态",
    prop: "status",
    width: 120,
    show: true,
    render: (row) => {
      const statusInfo = getStatusTag(row.status);
      return h(
        ElTag,
        { type: statusInfo.type, size: "small" },
        statusInfo.text
      );
    },
  },
  {
    label: "进度",
    prop: "progress",
    width: 150,
    show: true,
    render: (row) => {
      return h(ProgressBar, {
        progress: row.progress || 0,
        width: 120,
      });
    },
  },
  { label: "总场景", prop: "total_scenarios", width: 100, show: true },
  {
    label: "发现漏洞",
    prop: "vulnerable_count",
    width: 100,
    show: true,
    render: (row) => {
      return h(
        "span",
        { style: { color: "#f56c6c", fontWeight: "bold" } },
        row.vulnerable_count || 0
      );
    },
  },
  {
    label: "风险评分",
    prop: "risk_score",
    width: 100,
    show: true,
    render: (row) => {
      const score = row.risk_score || 0;
      let color = "#67c23a"; // 绿色 - 低风险
      if (score >= 70) color = "#f56c6c"; // 红色 - 高风险
      else if (score >= 40) color = "#e6a23c"; // 橙色 - 中风险

      return h("span", { style: { color, fontWeight: "bold" } }, score);
    },
  },
  { label: "开始时间", prop: "created_at", width: 180, show: true },
  {
    label: "操作",
    prop: "action",
    width: 300,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

const showCreateDialog = ref(false);
const showDetailDialog = ref(false);
const showResultDialog = ref(false);
const showReportDialog = ref(false);
const formRef = ref<DynamicFormInstance>();
const formData = reactive<any>({
  task_name: "",
  target_url: "",
  scenario_ids: [] as any[],
});

const createFormConfig: FormItemConfig[] = [
  {
    key: "task_name",
    name: "任务名称",
    type: "input",
    required: true,
    labelWidth: "120px",
    col: { span: 24 },
    placeholder: "请输入任务名称",
  },
  {
    key: "target_url",
    name: "目标URL",
    type: "input",
    required: true,
    labelWidth: "120px",
    col: { span: 24 },
    placeholder: "例如：https://example.com",
  },
  {
    key: "scenario_ids",
    name: "选择场景",
    type: "select",
    labelWidth: "120px",
    col: { span: 24 },
    params: {
      multiple: true,
      filterable: true,
      placeholder: "请选择要执行的场景",
    },
    options: [],
  },
];

const taskDetail = ref<any>(null);
const loadingDetail = ref(false);
const currentTaskId = ref("");
const reportData = ref<any>(null);
const loadingReport = ref(false);
const generatingReport = ref(false);

// 任务日志相关状态
const taskLogs = ref<any>(null);
const loadingLogs = ref(false);
const logLevel = ref("all"); // all/info/warn/error

const fetchTaskList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...searchForm,
    };
    Object.keys(params).forEach((key) => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });
    const { data } = await getTaskList(params);

    taskList.value = data?.tasks || [];
    pagination.total = data?.total || 0;
  } catch (error) {
    ElMessage.error("获取任务列表失败");
  } finally {
    loading.value = false;
  }
};

const fetchScenarioList = async () => {
  try {
    const { data } = await getScenarioList({
      page_size: 1000,
      is_active: true,
    });
    const scenarios = data?.scenarios || data || [];
    createFormConfig[2].options = scenarios.map((s: any) => ({
      label: `${s.scenario_name} (${s.scenario_code})`,
      value: s.id,
    }));
  } catch (error) {
    console.error("获取场景列表失败:", error);
  }
};

const handleSearch = (value: any) => {
  Object.assign(searchForm, value);
  pagination.currentPage = 1;
  fetchTaskList();
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  Object.assign(searchForm, { status: "", start_date: "", end_date: "" });
  pagination.currentPage = 1;
  fetchTaskList();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchTaskList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTaskList();
};

let refreshTimer: any = null;

const handleCloseCreateDialog = () => {
  showCreateDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(formData, { task_name: "", target_url: "", scenario_ids: [] });
};

const handleCreate = () => {
  showCreateDialog.value = true;
  Object.assign(formData, { task_name: "", target_url: "", scenario_ids: [] });
  if (createFormConfig[2].options?.length === 0) fetchScenarioList();
};

const fetchTaskLogs = async (taskId: string) => {
  if (!taskId) return;

  loadingLogs.value = true;
  try {
    const { data } = await getTaskLogs({
      task_id: taskId,
      level: logLevel.value,
    });
    taskLogs.value = data || null;
  } catch (error) {
    ElMessage.error("获取任务日志失败");
  } finally {
    loadingLogs.value = false;
  }
};

const handleViewDetail = async (row: any) => {
  loadingDetail.value = true;
  try {
    const { data } = await getTaskDetail({ task_id: row.task_id });
    taskDetail.value = data;
    showDetailDialog.value = true;
    // 同时获取任务日志
    logLevel.value = "all";
    await fetchTaskLogs(row.task_id);
  } catch (error) {
    ElMessage.error("获取任务详情失败");
  } finally {
    loadingDetail.value = false;
  }
};

const handleViewReport = async (row: any) => {
  currentTaskId.value = row.task_id;
  loadingReport.value = true;
  showReportDialog.value = true;
  try {
    const { data } = await getReportData({
      task_id: row.task_id,
      include_details: true,
    } as any);
    reportData.value = data || null;
  } catch (error) {
    ElMessage.error("获取报告数据失败");
  } finally {
    loadingReport.value = false;
  }
};

const handleGenerateHtmlReport = async () => {
  if (!currentTaskId.value) return;
  generatingReport.value = true;
  try {
    const { data } = await generateReport({
      task_id: currentTaskId.value,
      template: "comprehensive",
      include_charts: true,
      language: "zh-CN",
    } as any);
    const filename = data?.filename;
    if (!filename) {
      ElMessage.success("报告生成成功");
      return;
    }
    // 直接用 a 标签下载（接口返回完整HTML）
    const url = buildReportDownloadUrl(filename);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    a.target = "_blank";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  } catch (error) {
    ElMessage.error("报告生成失败");
  } finally {
    generatingReport.value = false;
  }
};

const handleCloseReportDialog = () => {
  showReportDialog.value = false;
  currentTaskId.value = "";
  reportData.value = null;
};

const handleLogLevelChange = (taskId: string) => {
  fetchTaskLogs(taskId);
};

const formatObjectJson = (obj: any) => {
  try {
    return JSON.stringify(obj, null, 2);
  } catch {
    return String(obj);
  }
};

const getLogLevelTag = (level: string) => {
  const levelMap: Record<string, any> = {
    info: { text: "信息", type: "info", color: "#409EFF" },
    warn: { text: "警告", type: "warning", color: "#E6A23C" },
    error: { text: "错误", type: "danger", color: "#F56C6C" },
    success: { text: "成功", type: "success", color: "#67C23A" },
  };
  return levelMap[level] || { text: level, type: "info", color: "#909399" };
};

const handleStart = async (row: any) => {
  ElMessageBox.confirm(`确定要启动任务 "${row.task_name}" 吗？`, "启动确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  }).then(async () => {
    try {
      // 任务创建后会自动异步执行，这里主要是刷新状态
      ElMessage.success("任务已启动，请等待系统自动执行");
      fetchTaskList();
    } catch (error) {
      ElMessage.error("启动失败");
    }
  });
};

const handlePause = async (row: any) => {
  try {
    await pauseTask({ task_id: row.task_id });
    ElMessage.success("任务已暂停");
    fetchTaskList();
  } catch (error) {
    ElMessage.error("暂停失败");
  }
};

const handleResume = async (row: any) => {
  try {
    await resumeTask({ task_id: row.task_id });
    ElMessage.success("任务已恢复");
    fetchTaskList();
  } catch (error) {
    ElMessage.error("恢复失败");
  }
};

const handleCancel = (row: any) => {
  ElMessageBox.confirm(`确定要取消任务 "${row.task_name}" 吗？`, "取消确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await cancelTask({ task_id: row.task_id });
      ElMessage.success("任务已取消");
      fetchTaskList();
    } catch (error) {
      ElMessage.error("取消失败");
    }
  });
};

const handleSubmitForm = async (submitData: any) => {
  try {
    await createTask({
      target_url: submitData.target_url,
      task_name: submitData.task_name,
      scenario_ids: Array.isArray(submitData.scenario_ids)
        ? submitData.scenario_ids
        : [],
    });
    ElMessage.success("任务创建成功");
    handleCloseCreateDialog();
    fetchTaskList();
  } catch (error) {
    ElMessage.error("创建失败");
  }
};

const handleViewResult = async (row: any) => {
  currentTaskId.value = row.task_id;
  showResultDialog.value = true;
};

const handleCloseResult = () => {
  showResultDialog.value = false;
  currentTaskId.value = "";
};

onMounted(() => {
  fetchTaskList();
  // 每30秒自动刷新任务列表
  // refreshTimer = setInterval(() => {
  //   fetchTaskList();
  // }, 30000);
});

onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        :columns="columns"
        :data="taskList"
        :loading="loading"
        :pagination="pagination"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" :icon="Plus" @click="handleCreate"
            >新建任务</el-button
          >
          <el-button type="primary" :icon="Refresh" @click="fetchTaskList"
            >刷新</el-button
          >
        </template>

        <template #action="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button
            v-if="row.status === 'completed'"
            type="success"
            size="small"
            @click="handleViewReport(row)"
          >
            查看报告
          </el-button>
          <el-button
            v-if="row.status === 'completed'"
            type="success"
            size="small"
            @click="handleViewResult(row)"
          >
            查看结果
          </el-button>
          <el-button
            v-if="row.status === 'pending'"
            type="success"
            size="small"
            @click="handleStart(row)"
          >
            开始
          </el-button>
          <el-button
            v-if="row.status === 'running'"
            type="warning"
            size="small"
            @click="handlePause(row)"
          >
            暂停
          </el-button>
          <el-button
            v-if="row.status === 'paused'"
            type="success"
            size="small"
            @click="handleResume(row)"
          >
            恢复
          </el-button>
          <el-button
            v-if="row.status === 'running' || row.status === 'paused'"
            type="danger"
            size="small"
            @click="handleCancel(row)"
          >
            取消
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <el-dialog
      v-model="showCreateDialog"
      title="创建任务"
      width="800px"
      @close="handleCloseCreateDialog"
    >
      <DynamicForm
        ref="formRef"
        v-model="formData"
        :form-config="createFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitForm"
        @cancel="handleCloseCreateDialog"
      />
    </el-dialog>

    <el-dialog v-model="showDetailDialog" title="任务详情" width="1200px">
      <div style="height: 600px; overflow-y: auto">
        <el-descriptions
          v-if="taskDetail"
          :column="2"
          border
          v-loading="loadingDetail"
        >
          <el-descriptions-item label="任务ID">{{
            taskDetail.task_id
          }}</el-descriptions-item>
          <el-descriptions-item label="任务名称">{{
            taskDetail.task_name
          }}</el-descriptions-item>
          <el-descriptions-item label="目标URL" :span="2">{{
            taskDetail.target_url
          }}</el-descriptions-item>
          <el-descriptions-item label="任务状态">
            <el-tag :type="getStatusTag(taskDetail.status).type">
              {{ getStatusTag(taskDetail.status).text }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="进度">
            <ProgressBar :progress="taskDetail.progress || 0" :width="200" />
          </el-descriptions-item>
          <el-descriptions-item label="总场景数">{{
            taskDetail.total_scenarios || 0
          }}</el-descriptions-item>
          <el-descriptions-item label="已完成场景">{{
            taskDetail.completed_scenarios || 0
          }}</el-descriptions-item>
          <el-descriptions-item label="发现漏洞">{{
            taskDetail.vulnerable_count || 0
          }}</el-descriptions-item>
          <el-descriptions-item label="安全通过">{{
            taskDetail.success_scenarios || 0
          }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{
            taskDetail.created_at
          }}</el-descriptions-item>
          <el-descriptions-item label="执行开始时间">{{
            taskDetail.started_at || "未开始"
          }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{
            taskDetail.completed_at || "未完成"
          }}</el-descriptions-item>
          <el-descriptions-item label="模板名称" :span="2">{{
            taskDetail.template_name || "未指定"
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 场景执行详情 -->
        <div
          v-if="taskDetail?.scenario_results?.length"
          style="margin-top: 20px"
        >
          <h4>场景执行详情</h4>
          <el-table :data="taskDetail.scenario_results" style="width: 100%">
            <el-table-column
              prop="scenario_name"
              label="场景名称"
              width="200"
            />
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status).type" size="small">
                  {{
                    row.status === "completed"
                      ? "已完成"
                      : row.status === "running"
                      ? "执行中"
                      : "等待中"
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="结果" width="120">
              <template #default="{ row }">
                <el-tag
                  :type="row.is_vulnerable ? 'danger' : 'success'"
                  size="small"
                >
                  {{ row.is_vulnerable ? "发现漏洞" : "安全" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="response_time" label="响应时间" width="120">
              <template #default="{ row }">
                {{ row.response_time ? `${row.response_time}s` : "-" }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 任务日志 -->
        <div v-if="taskLogs" style="margin-top: 20px">
          <h4>任务执行日志</h4>

          <!-- 基本信息 -->
          <el-card style="margin-bottom: 15px">
            <template #header>
              <span>基本信息</span>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="任务ID">{{
                taskLogs.task_id
              }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag
                  :type="taskLogs.status === 'completed' ? 'success' : 'info'"
                >
                  {{
                    taskLogs.status === "completed" ? "已完成" : taskLogs.status
                  }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="开始时间">{{
                taskLogs.create_time
              }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{
                taskLogs.end_time
              }}</el-descriptions-item>
              <el-descriptions-item label="日志目录" :span="2">{{
                taskLogs.log_directory
              }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 结果统计 -->
          <el-card v-if="taskLogs.result" style="margin-bottom: 15px">
            <template #header>
              <span>结果统计</span>
            </template>
            <div style="display: flex; gap: 20px">
              <div>
                <span style="color: #666">总场景数：</span>
                <span style="font-weight: bold">{{
                  taskLogs.result.total_scenarios
                }}</span>
              </div>
              <div>
                <span style="color: #666">发现漏洞：</span>
                <span style="font-weight: bold; color: #f56c6c">{{
                  taskLogs.result.vulnerable_count
                }}</span>
              </div>
              <div>
                <span style="color: #666">风险评分：</span>
                <span style="font-weight: bold; color: #e6a23c">{{
                  taskLogs.result.risk_score
                }}</span>
              </div>
            </div>
          </el-card>

          <!-- 请求详情 -->
          <el-card
            v-if="taskLogs.request_details?.length"
            style="margin-bottom: 15px"
          >
            <template #header>
              <span>请求详情 ({{ taskLogs.request_details.length }})</span>
            </template>
            <el-collapse>
              <el-collapse-item
                v-for="(req, index) in taskLogs.request_details"
                :key="index"
                :title="`请求 ${index + 1} - ${req.method} ${req.url}`"
              >
                <el-descriptions :column="1" border size="small">
                  <el-descriptions-item label="请求ID">{{
                    req.request_id
                  }}</el-descriptions-item>
                  <el-descriptions-item label="时间戳">{{
                    req.timestamp
                  }}</el-descriptions-item>
                  <el-descriptions-item label="方法">{{
                    req.method
                  }}</el-descriptions-item>
                  <el-descriptions-item label="URL">{{
                    req.url
                  }}</el-descriptions-item>
                  <el-descriptions-item label="载荷">
                    <el-input
                      :value="req.body?.payload || '-'"
                      type="textarea"
                      :rows="2"
                      readonly
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="请求头">
                    <el-input
                      :value="formatObjectJson(req.headers)"
                      type="textarea"
                      :rows="4"
                      readonly
                    />
                  </el-descriptions-item>
                </el-descriptions>
              </el-collapse-item>
            </el-collapse>
          </el-card>

          <!-- 响应详情 -->
          <el-card v-if="taskLogs.response_details?.length">
            <template #header>
              <span>响应详情 ({{ taskLogs.response_details.length }})</span>
            </template>
            <el-collapse>
              <el-collapse-item
                v-for="(resp, index) in taskLogs.response_details"
                :key="index"
                :title="`响应 ${index + 1} - 状态码: ${resp.status_code}`"
              >
                <el-descriptions :column="1" border size="small">
                  <el-descriptions-item label="请求ID">{{
                    resp.request_id
                  }}</el-descriptions-item>
                  <el-descriptions-item label="时间戳">{{
                    resp.timestamp
                  }}</el-descriptions-item>
                  <el-descriptions-item label="状态码">
                    <el-tag
                      :type="
                        resp.status_code >= 200 && resp.status_code < 300
                          ? 'success'
                          : 'danger'
                      "
                    >
                      {{ resp.status_code }}
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="响应头">
                    <el-input
                      :value="formatObjectJson(resp.headers)"
                      type="textarea"
                      :rows="4"
                      readonly
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="响应体">
                    <el-input
                      :value="
                        resp.body?.substring(0, 500) +
                        (resp.body?.length > 500 ? '...' : '')
                      "
                      type="textarea"
                      :rows="6"
                      readonly
                    />
                  </el-descriptions-item>
                </el-descriptions>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </div>

        <div v-else-if="loadingLogs" style="text-align: center; padding: 20px">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span style="margin-left: 10px">加载日志中...</span>
        </div>

        <div v-else style="text-align: center; color: #909399; padding: 20px">
          暂无日志数据
        </div>
      </div>
    </el-dialog>

    <!-- 查看报告对话框 -->
    <el-dialog
      v-model="showReportDialog"
      width="1000px"
      @close="handleCloseReportDialog"
    >
      <template #header>
        <div style="position: relative; padding-right: 140px">
          <span>任务报告</span>
          <el-button
            class="report-download-btn"
            type="primary"
            :loading="generatingReport"
            @click="handleGenerateHtmlReport"
          >
            生成HTML并下载
          </el-button>
        </div>
      </template>
      <div
        v-loading="loadingReport"
        style="height: 70vh; overflow-y: auto; position: relative"
      >
        <template v-if="reportData">
          <el-descriptions title="报告概览" :column="2" border>
            <el-descriptions-item label="报告ID">
              {{ reportData.metadata?.report_id || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="生成时间">
              {{ reportData.metadata?.generated_at || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="统计周期">
              {{ reportData.metadata?.period || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="总任务数">
              <el-tag type="info">{{
                reportData.metadata?.total_tasks ?? 0
              }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <div style="margin-top: 16px">
            <h4>高层总结</h4>
            <el-descriptions :column="4" border>
              <el-descriptions-item label="总漏洞数">
                <el-tag type="danger">{{
                  reportData.executive_summary?.total_vulnerabilities ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="关键问题">
                <el-tag type="danger">{{
                  reportData.executive_summary?.critical_findings ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="整体风险分">
                <el-tag type="warning">{{
                  reportData.executive_summary?.overall_risk_score ?? "-"
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="趋势">
                {{ reportData.executive_summary?.improvement_trend || "-" }}
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions :column="2" border style="margin-top: 12px">
              <el-descriptions-item label="业务影响">
                {{ reportData.executive_summary?.business_impact || "-" }}
              </el-descriptions-item>
              <el-descriptions-item label="风险评级">
                {{ reportData.executive_summary?.risk_rating || "-" }}
              </el-descriptions-item>
              <el-descriptions-item label="安全评分">
                <el-tag type="success">{{
                  reportData.executive_summary?.security_score ?? "-"
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="测试向量数">
                <el-tag type="info">{{
                  reportData.executive_summary?.total_attack_vectors_tested ?? 0
                }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div
              v-if="reportData.executive_summary?.key_findings?.length"
              style="margin-top: 12px"
            >
              <h4>关键发现</h4>
              <ul>
                <li
                  v-for="(kf, i) in reportData.executive_summary.key_findings"
                  :key="i"
                >
                  {{ kf }}
                </li>
              </ul>
            </div>

            <div
              v-if="reportData.executive_summary?.severity_distribution"
              style="margin-top: 12px"
            >
              <h4>严重度分布</h4>
              <el-descriptions :column="4" border>
                <el-descriptions-item label="Critical">
                  <el-tag type="danger">{{
                    reportData.executive_summary.severity_distribution
                      .critical ?? 0
                  }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="High">
                  <el-tag type="danger">{{
                    reportData.executive_summary.severity_distribution.high ?? 0
                  }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="Medium">
                  <el-tag type="warning">{{
                    reportData.executive_summary.severity_distribution.medium ??
                    0
                  }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="Low">
                  <el-tag type="success">{{
                    reportData.executive_summary.severity_distribution.low ?? 0
                  }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>

          <div style="margin-top: 16px">
            <h4>漏洞按严重等级</h4>
            <el-descriptions :column="4" border>
              <el-descriptions-item label="Critical">
                <el-tag type="danger">{{
                  reportData.vulnerability_analysis?.by_severity?.critical ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="High">
                <el-tag type="danger">{{
                  reportData.vulnerability_analysis?.by_severity?.high ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="Medium">
                <el-tag type="warning">{{
                  reportData.vulnerability_analysis?.by_severity?.medium ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="Low">
                <el-tag type="success">{{
                  reportData.vulnerability_analysis?.by_severity?.low ?? 0
                }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-if="reportData.attack_surface" style="margin-top: 16px">
            <h4>攻击面概览</h4>
            <el-descriptions :column="4" border>
              <el-descriptions-item label="可用攻击向量">
                <el-tag type="info">{{
                  reportData.attack_surface.attack_vectors_available ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="暴露目标数">
                <el-tag type="warning">{{
                  reportData.attack_surface.exposed_targets ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="易受攻击端点">
                <el-tag type="danger">{{
                  reportData.attack_surface.vulnerable_endpoints ?? 0
                }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="暴露端口">
                {{
                  (reportData.attack_surface.exposed_ports || []).join(", ") ||
                  "N/A"
                }}
              </el-descriptions-item>
            </el-descriptions>
            <div
              v-if="reportData.attack_surface.target_details?.length"
              style="margin-top: 10px"
            >
              <el-table :data="reportData.attack_surface.target_details" border>
                <el-table-column prop="target" label="目标" />
                <el-table-column
                  prop="vulnerabilities"
                  label="漏洞数"
                  width="100"
                />
              </el-table>
            </div>
          </div>

          <div v-if="reportData.compliance_mapping" style="margin-top: 16px">
            <h4>合规映射</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="ISO 27001">
                <div>
                  <div
                    v-for="(item, i) in reportData.compliance_mapping
                      .iso_27001 || []"
                    :key="'iso' + i"
                  >
                    {{ item }}
                  </div>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="NIST CSF">
                <div>
                  <div
                    v-for="(item, i) in reportData.compliance_mapping
                      .nist_csf || []"
                    :key="'nist' + i"
                  >
                    {{ item }}
                  </div>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="PCI DSS" :span="2">
                <div>
                  <div
                    v-for="(item, i) in reportData.compliance_mapping.pci_dss ||
                    []"
                    :key="'pci' + i"
                  >
                    {{ item }}
                  </div>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="OWASP Top 10" :span="2">
                <el-table
                  :data="reportData.compliance_mapping.owasp_top_10 || []"
                  border
                >
                  <el-table-column prop="category" label="类别" />
                  <el-table-column
                    prop="violations"
                    label="违规计数"
                    width="120"
                  />
                </el-table>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-if="reportData.security_posture" style="margin-top: 16px">
            <h4>安全态势</h4>
            <div style="margin-bottom: 10px">
              <h5>按攻击类别</h5>
              <el-table
                :data="reportData.security_posture.by_attack_category || []"
                border
              >
                <el-table-column prop="category" label="类别" />
                <el-table-column
                  prop="total_tests"
                  label="测试数"
                  width="100"
                />
                <el-table-column
                  prop="vulnerabilities"
                  label="漏洞数"
                  width="100"
                />
                <el-table-column prop="pass_rate" label="通过率" width="120">
                  <template #default="{ row }">{{ row.pass_rate }}%</template>
                </el-table-column>
              </el-table>
            </div>
            <div>
              <h5>按威胁类型</h5>
              <el-table
                :data="reportData.security_posture.by_threat_type || []"
                border
              >
                <el-table-column prop="type" label="类型" />
                <el-table-column
                  prop="total_tests"
                  label="测试数"
                  width="100"
                />
                <el-table-column
                  prop="vulnerabilities"
                  label="漏洞数"
                  width="100"
                />
                <el-table-column prop="pass_rate" label="通过率" width="120">
                  <template #default="{ row }">{{ row.pass_rate }}%</template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div
            v-if="reportData.risk_trends?.daily_statistics?.length"
            style="margin-top: 16px"
          >
            <h4>风险趋势（日统计）</h4>
            <el-table :data="reportData.risk_trends.daily_statistics" border>
              <el-table-column prop="date" label="日期" width="140" />
              <el-table-column
                prop="tests_conducted"
                label="测试数"
                width="120"
              />
              <el-table-column
                prop="vulnerabilities_found"
                label="发现漏洞"
                width="120"
              />
              <el-table-column
                prop="vulnerability_rate"
                label="漏洞率(%)"
                width="140"
              />
            </el-table>
          </div>

          <div
            v-if="reportData.remediation_priorities"
            style="margin-top: 16px"
          >
            <h4>整改优先级</h4>
            <div
              v-for="(section, key) in reportData.remediation_priorities"
              :key="key"
              style="margin-bottom: 12px"
            >
              <h5>{{ section.priority_name }}（{{ section.timeline }}）</h5>
              <el-descriptions :column="3" border>
                <el-descriptions-item label="项数">
                  <el-tag type="info">{{ section.count || 0 }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
              <el-table
                v-if="section.items?.length"
                :data="section.items"
                border
                style="margin-top: 8px"
              >
                <el-table-column prop="vulnerability" label="漏洞" />
                <el-table-column prop="cve" label="CVE" width="160" />
                <el-table-column prop="target" label="目标" />
                <el-table-column
                  prop="estimated_effort"
                  label="预计工作量"
                  width="140"
                />
                <el-table-column prop="mitigation" label="缓解方案" />
              </el-table>
            </div>
          </div>

          <div
            v-if="reportData.detailed_findings?.length"
            style="margin-top: 16px"
          >
            <h4>详细发现</h4>
            <el-table :data="reportData.detailed_findings" border>
              <el-table-column prop="title" label="标题" width="260" />
              <el-table-column prop="severity" label="严重度" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="
                      row.severity === 'critical'
                        ? 'danger'
                        : row.severity === 'high'
                        ? 'danger'
                        : row.severity === 'medium'
                        ? 'warning'
                        : 'info'
                    "
                    >{{ row.severity }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column prop="cvss_score" label="CVSS" width="90" />
              <el-table-column
                prop="detected_at"
                label="发现时间"
                width="160"
              />
              <el-table-column prop="location.url" label="URL">
                <template #default="{ row }">{{ row.location?.url }}</template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px">
              <el-descriptions
                v-for="(f, i) in reportData.detailed_findings"
                :key="'fd' + i"
                :column="2"
                border
                style="margin-bottom: 10px"
              >
                <el-descriptions-item label="描述">{{
                  f.description
                }}</el-descriptions-item>
                <el-descriptions-item label="检测方法">{{
                  f.evidence?.detection_method || "N/A"
                }}</el-descriptions-item>
                <el-descriptions-item label="Payload">{{
                  f.evidence?.payload_used || f.evidence?.payload || "-"
                }}</el-descriptions-item>
                <el-descriptions-item label="响应时间">{{
                  f.evidence?.response_time || "-"
                }}</el-descriptions-item>
                <el-descriptions-item label="响应码">{{
                  f.evidence?.response_status ?? "-"
                }}</el-descriptions-item>
                <el-descriptions-item label="影响评估" :span="2">
                  机密性:
                  {{ f.impact_assessment?.confidentiality || "-" }}，完整性:
                  {{ f.impact_assessment?.integrity || "-" }}，可用性:
                  {{ f.impact_assessment?.availability || "-" }}，业务影响:
                  {{ f.impact_assessment?.business_impact || "-" }}
                </el-descriptions-item>
                <el-descriptions-item label="修复建议" :span="2">
                  优先级: {{ f.remediation?.priority || "-" }}，预计工作量:
                  {{ f.remediation?.effort || "-" }}，步骤:
                  {{ f.remediation?.steps || "-" }}
                </el-descriptions-item>
                <el-descriptions-item label="威胁类型">{{
                  f.vulnerability_details?.type || "-"
                }}</el-descriptions-item>
                <el-descriptions-item label="CVE">{{
                  f.vulnerability_details?.cve || "-"
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>

          <div
            v-if="reportData.recommendations?.length"
            style="margin-top: 16px"
          >
            <h4>总体建议</h4>
            <div
              v-for="(recGroup, i) in reportData.recommendations"
              :key="'rec' + i"
              style="margin-bottom: 12px"
            >
              <h5>
                {{ recGroup.category }}（优先级：{{ recGroup.priority }}）
              </h5>
              <ul>
                <li
                  v-for="(r, j) in recGroup.recommendations"
                  :key="'recItem' + j"
                >
                  {{ r }}
                </li>
              </ul>
            </div>
          </div>
        </template>
      </div>
    </el-dialog>

    <!-- 结果查看组件 -->
    <TaskResult
      :task-id="currentTaskId"
      :visible="showResultDialog"
      @close="handleCloseResult"
    />
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.report-download-btn {
  position: absolute;
  top: 0;
  right: 24px;
  z-index: 10;
}
</style>
